﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Diagnostics;
using System.Linq;
using System.Web;

namespace Hangout.Web.Core.BackgroundData
{
    public class UserBackgroundData
    {
        public static List<int> GetOutDatedCompatibilityScoreUserIds(TimeSpan olderThan, ref Model.HangoutDBEntities context)
        {
            try
            {
                List<int> ids = new List<int>();
                ids.AddRange(context.Users.Where(o => o.UserBackgroundData == null).Select(o => o.UserID).ToList());
                
                ids.AddRange(context.Users.Where(o => o.UserBackgroundData != null && o.UserBackgroundData.CompatibilityCheckDateTimeStamp == null).Select(o => o.UserID).ToList());//add all the user which dont have compatibility score. :)
                
                ids.AddRange(context.Users.Select(o => o.UserBackgroundData).Where(o => o != null).Where(o => o.CompatibilityCheckDateTimeStamp != null).Where(o => EntityFunctions.DiffMinutes(DateTime.Now, o.CompatibilityCheckDateTimeStamp) >= olderThan.TotalMinutes).Select(o => o.UserID).ToList()); //add all the outdated users
                
                return ids;
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
                return null;
            }


        }

        public static void UpdateCompatibilityDateTimeStamp(int userId,ref Model.HangoutDBEntities context)
        {
            bool flag = false;
            Model.UserBackgroundData data;
            if (!HasBackgroundInfo(userId, context))
            {
                data = new Model.UserBackgroundData();
                data.UserID = userId;
                flag = true;
            }
            else
            {
                data = GetBackgroundInfo(userId, context);
            }

            data.CompatibilityCheckDateTimeStamp = DateTime.Now;//update compatibility date time :)

            if (flag)
            {
                context.AddToUserBackgroundDatas(data);
            }

            context.SaveChanges();
        }

        public static bool HasBackgroundInfo(int userid, Model.HangoutDBEntities context)
        {
            if (context.UserBackgroundDatas.Where(o => o.UserID == userid).SingleOrDefault()==null)
            {
                return false;
            }

            return true;
        }

        public static Model.UserBackgroundData GetBackgroundInfo(int userid, Model.HangoutDBEntities context)
        {
            return context.UserBackgroundDatas.Where(o => o.UserID == userid).SingleOrDefault();
           
        }
    }
}